// api/request.js
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'

const request = axios.create({
    baseURL: 'http://localhost:8080/api',
    timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        // 默认需要认证，除非明确设置 needAuth: false
        const needAuth = config.needAuth !== false

        if (needAuth) {
            const authStore = useAuthStore()
            const token = authStore.getToken()
            // console.log("token:"+token)
            if (token && config.headers) {
                config.headers.Authorization = `Bearer ${token}`
            } else if (needAuth) {
                console.error('接口需要认证但未登录:', config.url)
            }
        } else {
            // 明确不需要认证的接口，删除可能存在的token
            if (config.headers) {
                delete config.headers.Authorization
            }
        }

        return config
    },
    (error) => Promise.reject(error)
)

// 响应拦截器也可以加
// 封装完整的请求方法
const createHttpMethods = (needAuth = true) => {
    const config = { needAuth }

    return {
        get: (url, params = {}, requestConfig = {}) =>
            request.get(url, { params, ...config, ...requestConfig }),

        post: (url, data = {}, requestConfig = {}) =>
            request.post(url, data, { ...config, ...requestConfig }),

        put: (url, data = {}, requestConfig = {}) =>
            request.put(url, data, { ...config, ...requestConfig }),

        patch: (url, data = {}, requestConfig = {}) =>
            request.patch(url, data, { ...config, ...requestConfig }),

        delete: (url, params = {}, requestConfig = {}) =>
            request.delete(url, { params, ...config, ...requestConfig }),
    }
}

export const http = {
    // 需要认证的请求（默认）
    secure: createHttpMethods(true),

    // 不需要认证的请求
    public: createHttpMethods(false)
}

export default request